package com.kpx.app.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.kpx.app.R;
import com.kpx.app.base.ActivityBase;
import com.kpx.app.bean.ExtacInfoBean;
import com.kpx.app.bean.LoginUser;
import com.kpx.app.bean.Wallet;
import com.kpx.app.http.HttpDataApi;
import com.kpx.app.http.HttpDataLoader;
import com.kpx.app.http.HttpDataReqUrl;
import com.kpx.app.http.HttpDataRequest;
import com.kpx.app.http.ResObj;
import com.kpx.app.utils.MD5Util;
import com.kpx.app.utils.MyHashMap;
import com.kpx.app.utils.UIUtils;
import com.kpx.app.utils.UserInfoUtils;
import com.kpx.app.utils.uiutils.IntentUtil;
import com.kpx.app.utils.uiutils.ToastUtil;
import com.kpx.app.view.TitleView;
import com.kpx.app.wigdet.DialogWithdrawInputPwd;

import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by congdy on 17/3/6.
 * 提现页面
 */

public class ActivityWithdrawals extends ActivityBase {
    @BindView(R.id.titleview)
    TitleView titleview;
    @BindView(R.id.txt_withdrawals_all)
    TextView txtWithdrawalsAll;
    @BindView(R.id.et_price)
    EditText etPrice;
    @BindView(R.id.txt_clear)
    TextView txtClear;
    @BindView(R.id.txt_current_price)
    TextView txtCurrentPrice;
    @BindView(R.id.txt_shouxufei)
    TextView txtShouxufei;
    @BindView(R.id.btn_withdrawals)
    Button btnWithdrawals;
    @BindView(R.id.txt_lest_price)
    TextView txtLestPrice;
    @BindView(R.id.txt_bind_card)
    TextView txt_bind_card;
    @BindView(R.id.ll_add_count)
    LinearLayout llAddCount;
    @BindView(R.id.ll_set_wpwd)
    LinearLayout llSetWpwd;
    DecimalFormat df = new DecimalFormat("###0.00");
    private Wallet wallet;
    private ExtacInfoBean.ACCOUNTBean accountBean;
    private ExtacInfoBean b;

    @Override
    public void initview(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_withdrawals);
        ButterKnife.bind(this);
        UIUtils.setNormalTitle(titleview, "提现");
    }

    /**
     * EXTRACT_PERCENT（提现手续费百分比），ACCOUNT（绑定的账户实体，没有时为NULL）,SHOW(1：表示显示手续费，2或者其它表示不显示)
     */
    private void getTxInfo() {
        showLoadingDialog();
        MyHashMap map = new MyHashMap();
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                dissmissLoadingDialog();
                if (result.getCode() == 0) {
                    b = (ExtacInfoBean) result.getData();
                    if (b != null) {
                        accountBean = b.getACCOUNT();
                        txtShouxufei.setVisibility(b.getSHOW()==1?View.VISIBLE:View.GONE);
                        if(accountBean!=null){
                            txt_bind_card.setText(accountBean.getAccountNumber());
                        }
                    }
                } else {
                    ToastUtil.getInstance().showToast(ActivityWithdrawals.this, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                dissmissLoadingDialog();
                ToastUtil.getInstance().showToast(ActivityWithdrawals.this, error);
            }

        }, ExtacInfoBean.class, HttpDataRequest.TYPE_OBJECT).POST(HttpDataReqUrl.URL_POST_INFO_TIXIAN, true, map);
    }

    @Override
    public void initData() {
        setSxf(0);
        etPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(etPrice.getText().toString().trim()) && wallet != null) {
                    Double input = Double.valueOf(etPrice.getText().toString().trim());
                    if(b==null){
                        getTxInfo();
                        ToastUtil.getInstance().showToast(ActivityWithdrawals.this,"提现数据有误，正在重新获取中");
                    }
                    setSxf(b.getEXTRACT_PERCENT()*input/100);
                    if (input > wallet.getCashAmount()) {
                        txtCurrentPrice.setTextColor(getResources().getColor(R.color.red));
                        txtCurrentPrice.setText("输入金额超过账户余额");
                        txtWithdrawalsAll.setVisibility(View.GONE);
                    } else {
                        txtWithdrawalsAll.setVisibility(View.VISIBLE);
                        txtCurrentPrice.setTextColor(getResources().getColor(R.color.red));
                        txtCurrentPrice.setText("当前账户余额 ¥" + df.format(wallet.getCashAmount()));
                    }
                }
            }
        });
    }

    private void setSxf(double show) {
        String name = "¥" + df.format(show);
        String str = "手续费 " + name;
        SpannableString s = new SpannableString(str);
        Pattern p = Pattern.compile(name);
        Matcher m = p.matcher(s);
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.red_FF4088)), start, end,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        txtShouxufei.setText(s);
    }

    @Override
    public void onReceiver(Context context, Intent intent) {

    }

    @OnClick({R.id.txt_withdrawals_all, R.id.txt_clear, R.id.btn_withdrawals, R.id.ll_add_count, R.id.ll_set_wpwd})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.txt_withdrawals_all:
                etPrice.setText(((int)wallet.getCashAmount()/100)*100+"");
                break;
            case R.id.txt_clear:
                break;
            case R.id.btn_withdrawals:
                if (TextUtils.isEmpty(etPrice.getText().toString().trim())) {
                    ToastUtil.getInstance().showToast(ActivityWithdrawals.this, "请输入提现金额");
                    return;
                }
                if (!TextUtils.isEmpty(etPrice.getText().toString().trim())&&Double.valueOf(etPrice.getText().toString().trim())==0) {
                    ToastUtil.getInstance().showToast(ActivityWithdrawals.this, "请输入提现金额");
                    return;
                }
                if (accountBean == null) {
                    ToastUtil.getInstance().showToast(ActivityWithdrawals.this, "请先绑定提现账户");
                    return;
                }
                if (wallet!=null&&wallet.getHasPwd()==0) {
                    ToastUtil.getInstance().showToast(ActivityWithdrawals.this, "请先设置提现密码");
                    return;
                }
                final DialogWithdrawInputPwd p = new DialogWithdrawInputPwd(this);
                p.setAmount(etPrice.getText().toString().trim());
                p.setOperateText("提现金额");
                p.setOnInputListener(new DialogWithdrawInputPwd.OnInputListener() {
                    @Override
                    public void inputDone(String pwd) {
                        p.dismiss();
                        toTx(pwd);
                    }
                });
                p.show();
                break;
            case R.id.ll_add_count:
                IntentUtil.gotoActivity(ActivityWithdrawals.this, ActivityAddTxCard.class);
                break;
            case R.id.ll_set_wpwd:
                IntentUtil.gotoActivity(ActivityWithdrawals.this, ActivityResetTxPwd.class);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        showLoadingDialog();
        getTxInfo();
        UserInfoUtils.getMyWallet(ActivityWithdrawals.this, new UserInfoUtils.OnGetMyWalletBackListener() {
            @Override
            public void back(Wallet aBeans) {
                dissmissLoadingDialog();
                if (aBeans != null) {
                    ActivityWithdrawals.this.wallet = aBeans;
                    txtCurrentPrice.setText("当前账户余额 ¥" + df.format(aBeans.getCashAmount()));

                }
            }
        });
    }

    /**
     * 参数：token,Double money, Long account, String pwd
     * @param pwd
     */
    private void toTx(String pwd) {
        showLoadingDialog();
        MyHashMap map = new MyHashMap();
        map.put("money", etPrice.getText().toString().trim());
        if(accountBean!=null){
            map.put("account", accountBean.getDmId()+"");
        }else {
            getTxInfo();
        }
        map.put("pwd", MD5Util.encrypt(pwd));
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                dissmissLoadingDialog();
                if (result.getCode() == 0) {
                    ToastUtil.getInstance().showToast(ActivityWithdrawals.this, "提现成功");
                    ActivityWalletDetailList.inType = ActivityWalletDetailList.TYPE_DETAIL_WITH;
                    IntentUtil.gotoActivityAndFinish(ActivityWithdrawals.this, ActivityWalletDetailList.class);
                } else {
                    ToastUtil.getInstance().showToast(ActivityWithdrawals.this, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                dissmissLoadingDialog();
                ToastUtil.getInstance().showToast(ActivityWithdrawals.this, error);
            }

        }, null, null).POST(HttpDataReqUrl.URL_GET_WALLET_EXTRACT, true, map);
    }
}
